package com.lcm.springcloud.controller;

import com.lcm.springcloud.common.ResultBean;
import com.lcm.springcloud.lb.LoadBalancer;
import com.lcm.springcloud.param.PaymentParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.net.URI;
import java.util.List;

/**
 * @author: Coder-Lcm
 * @date: 2020/10/26 18:09
 */
@RestController
@Slf4j
public class OrderController {

    /**单机版可以写死IP地址*/
//    private static final String PAYMENT_URL = "http://localhost:8001";
    /*集群的情况下要写服务名称，因为同一个服务名称可以有多个服务提供者（集群）*/
    private static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource //引入自定义的负载均衡算法
    private LoadBalancer loadBalancer;

    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/consumer/payment/add")
    public ResultBean addPayment(@RequestBody PaymentParam payment){
        log.info("80" + payment);
        return restTemplate.postForObject(PAYMENT_URL + "/payment/add", payment , ResultBean.class);
    }

    @GetMapping("/consumer/payment/{id}")
    public ResultBean<PaymentParam> getById1(@PathVariable("id") @NotNull Long id){
        return restTemplate.getForObject(PAYMENT_URL + "/payment/" + id, ResultBean.class);
    }

    /**
     * restTemplate 的getForEntity：
     *      返回对象为ResponseEntity，包含了响应的一些重要信息，如响应头，状态码，响应体等。
     * 而 getForObject返回的是数据转换成的对象，一般是json
     * @param id
     * @return
     */
    @GetMapping("/consumer/payment/getForEntity/{id}")
    public ResultBean<PaymentParam> getById2(@PathVariable("id") @NotNull Long id){
        ResponseEntity<ResultBean> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/" + id, ResultBean.class);
        if (entity.getStatusCode().is2xxSuccessful()) {
            //2xx状态码表示响应正常
            return entity.getBody();
        }else {
            return new ResultBean<>(444, "操作失败");
        }
    }

    /**
     * 用于演示自定义的负载均衡策略：轮询
     * @return
     */
    @GetMapping("/consumer/payment/lb")
    public String getPaymentLB(){
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (null == instances || instances.size() <= 0) {
            return "当前没有CLOUD-PAYMENT-SERVICE服务实例对象";
        }
        ServiceInstance serviceInstance = loadBalancer.instances(instances);
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri + "/payment/lb", String.class);
    }

    /**
     * 用于测试zipkin + sleuth实现的链路调用监控
     * @return
     */
    @GetMapping("/consumer/payment/zipkin")
    public String paymentZipkin(){
        String r = restTemplate.getForObject("http://localhost:8001" + "/payment/zipkin/", String.class);
        return r;
    }

}
